package com.springboot.bigevent.controller;

import com.springboot.bigevent.pojo.Result;
import com.springboot.bigevent.pojo.User;
import com.springboot.bigevent.service.UserService;
import com.springboot.bigevent.utils.JwtUtil;
import com.springboot.bigevent.utils.Md5Util;
import com.springboot.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.apache.tomcat.util.buf.StringUtils;
import org.hibernate.validator.constraints.URL;
import org.hibernate.validator.internal.constraintvalidators.bv.time.futureorpresent.FutureOrPresentValidatorForReadableInstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Validated
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //查询用户是否被占用
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){


        User u = userService.findByUsername(username);
        if(u == null){
            //未被占用
            //注册
            userService.register(username,password);
            return Result.success();
        }
        else {
            return Result.error("用户名已被占用");
        }

    }

    //根据用户名查询用户
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$")String password)
    {

        User loginuser = userService.findByUsername(username);
        //判断用户是否存在
        if (loginuser == null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        if (Md5Util.getMD5String(password).equals(loginuser.getPassword())){
            //登录成功
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id",loginuser.getId());
            claims.put("username",loginuser.getUsername());
            String token = JwtUtil.genToken(claims);
            //把token存储在redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    //根据用户名查询用户
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/){

        /*Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");*/
        //使用ThreadLocal优化代码
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User name = userService.findByUsername(username);
        return Result.success(name);
    }

    //更新用户基本信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){//当属性被封装到pojo中，需要在pojo类中使用注解进行校验
        userService.update(user);
        return Result.success();
    }

    //更新用户头像
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestBody @URL String avatarUrl){//@URL注解用于校验url格式
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    //重置用户密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody @Pattern(regexp = "^\\S{5,16}$") Map<String,String> params,@RequestHeader(name = "Authorization") String token){//完成密码修改后，从请求头获取token
        //1.检验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");


        if(!org.springframework.util.StringUtils.hasLength(oldPwd) || !org.springframework.util.StringUtils.hasLength(newPwd) || !org.springframework.util.StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要参数");
        }

        //原密码是否正确
        //调用userService使用用户名拿到密码，再与oldPwd比对
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        if(!Md5Util.getMD5String(oldPwd).equals(user.getPassword())) {
            return Result.error("原密码错误");
        }
        if(!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }

        //调用service完成密码更新
        userService.updatePwd(newPwd);

        //完成密码更新后，删除对应token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getAndDelete(token);
        return Result.success();
    }
}
